To interact with AWS Lambda using the AWS SDK in JavaScript, you can import the SDK, initialize an AWS Lambda client, and invoke a Lambda function with a custom payload. The AWS Lambda client handles potential errors and success cases by calling context.done
in case of an error and context.succeed
with the payload in case of a successful function call.
var aws = require('aws-sdk');
var lambda = new aws.Lambda({
region: 'us-west-2' //change to your region
});
lambda.invoke({
FunctionName: 'name_of_your_lambda_function',
Payload: JSON.stringify(event, null, 2) // pass params
}, function(error, data) {
if (error) {
context.done('error', error);
}
if(data.Payload){
context.succeed(data.Payload)
}
});
/**
* Import the required AWS SDK and set the region.
* @type {Object} aws - AWS SDK instance
*/
const { Lambda } = require('aws-sdk');
const lambda = new Lambda({
region: process.env.AWS_REGION || 'us-west-2', // Use AWS_REGION env var if set, default to us-west-2
});
/**
* Invoke the Lambda function with the provided event data.
* @param {Object} event - Event data to pass to the Lambda function
* @param {Function} callback - Callback function to handle the response
*/
function invokeLambda(event, callback) {
const params = {
FunctionName: 'name_of_your_lambda_function',
Payload: JSON.stringify(event, null, 2), // pass params
};
lambda.invoke(params, (error, data) => {
if (error) {
callback('error', error);
} else if (data.Payload) {
callback(null, data.Payload);
} else {
callback('error', new Error('No payload in response')); // Add error handling for unexpected response
}
});
}
// Example usage
invokeLambda(event, (error, result) => {
if (error) {
console.error(error); // Log errors to cloudwatch
} else {
console.log(result); // Log successful response to cloudwatch
}
});
var aws = require('aws-sdk');
Imports the AWS SDK.
var lambda = new aws.Lambda({
region: 'us-west-2' // change to your region
});
Creates a new client instance for AWS Lambda in the specified region.
lambda.invoke({
FunctionName: 'name_of_your_lambda_function', // replace with your function name
Payload: JSON.stringify(event, null, 2) // pass params
}, function(error, data) {
...
});
Invokes the specified Lambda function with the provided payload, which is a JSON stringified version of the event
object.
if (error) {
context.done('error', error);
}
if (data.Payload) {
context.succeed(data.Payload)
}
Handles potential errors and success cases.
context.done
with an error message and the error object.context.succeed
with the payload.